package designpattern.adapter.order;

import designpattern.adapter.order.domain.ElemeOrder;
import designpattern.adapter.order.domain.MeituanOrder;
import designpattern.adapter.order.domain.OrderInfo;
import designpattern.adapter.order.domain.QianLanOrder;
import com.alibaba.fastjson.JSON;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 刘牌
 * @Date: 2021/12/20/15:27
 * @Description:
 */
public class ThirdOrderAdapter extends OrderServiceImpl implements IThirdOrderService , IQianLanOrderService {
    @Override
    public String meiTuanOrder(MeituanOrder meituanOrder , Map<String,String> filedMappingList) {
        return super.saveOrder(converter(meituanOrder,filedMappingList));
    }

    @Override
    public String elemeOrder(ElemeOrder elemeOrder , Map<String,String> filedMappingList) {
        return super.saveOrder(converter(elemeOrder,filedMappingList));
    }

    /**
     * 转换器
     * @param obj
     * @param filedMappingList
     * @return
     */
    private OrderInfo converter(Object obj , Map<String , String> filedMappingList){
        String jsonString = JSON.toJSONString(obj);
        Map object = JSON.parseObject(jsonString, Map.class);
        OrderInfo orderInfo = new OrderInfo();
        filedMappingList.forEach((key,value) -> {
            Object o = object.get(filedMappingList.get(key));
            try {
                OrderInfo.class.getMethod("set" + key.substring(0,1).toUpperCase() + key.substring(1),String.class).invoke(orderInfo,o.toString());
            } catch (InvocationTargetException | IllegalAccessException | NoSuchMethodException e) {
                e.printStackTrace();
            }
        });
        return orderInfo;
    }

    @Override
    public String qianLanOrder(QianLanOrder qianLanOrder , Map<String , String> filedMappingList) {
        return super.saveOrder(converter(qianLanOrder,filedMappingList));
    }
}
